package com.example.medical.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.medical.entity.dto.*;
import com.example.medical.entity.pojo.Admin;
import com.example.medical.service.AdminService;
import com.example.medical.mapper.AdminMapper;
import com.example.medical.utils.common.enums.Code;
import com.example.medical.utils.common.enums.Jwt;
import com.example.medical.utils.common.enums.Message;
import com.example.medical.utils.common.result.PageResponseResult;
import com.example.medical.utils.common.result.Result;
import com.example.medical.utils.config.BaseContext;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
* @author 24354
* @description 针对表【admin】的数据库操作Service实现
* @createDate 2024-03-31 22:41:50
*/
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin>
    implements AdminService{

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public Result AdminLogin(LoginDto dto) {
        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Admin checkAdmin = adminMapper.selectOne(Wrappers.<Admin>lambdaQuery().eq(Admin::getAdminName, dto.getUsername()));
        if (checkAdmin==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        if (!checkAdmin.getAdminPassword().equals(DigestUtils.md5Hex(dto.getPassword()))) {
            return Result.errorResult(Code.LOGIN_PASSWORD_ERROR);
        }
        String id= String.valueOf(checkAdmin.getAdminId());
        String token = Jwts.builder()
                .setHeaderParam(Message.Jwt_Alg, Jwt.Admin_Jwt_Key.getAlg())
                .setHeaderParam(Message.Jwt_Typ, Jwt.Admin_Jwt_Key.getTyp())
                .setSubject(Jwt.Admin_Jwt_Key.getName())
                .setExpiration(new Date(System.currentTimeMillis() + Jwt.Admin_Jwt_Key.getExp()))
                .claim(Message.Admin_id,id )
                .signWith(SignatureAlgorithm.HS256, Jwt.Admin_Jwt_Key.getKey())
                .compact();
        return Result.okResult(token);
    }

    @Override
    public Result UpdateAdminPassword(UpdatePasswordDto dto) {
        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long adminId = BaseContext.getCurrentId();
        Admin checkAdmin = adminMapper.selectById(adminId);
        if (checkAdmin==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        if (!checkAdmin.getAdminPassword().equals(DigestUtils.md5Hex(dto.getOldPassword()))) {
            return Result.errorResult(Code.LOGIN_PASSWORD_ERROR);
        }
        if (!dto.getNewPassword().equals(dto.getNewPasswordCopy())) {
            return Result.errorResult(Code.PARAM_INVALID);
        }
        checkAdmin.setPassword(dto.getNewPassword());
        checkAdmin.setAdminPassword(DigestUtils.md5Hex(dto.getNewPassword()));
        boolean checkUpdate = updateById(checkAdmin);
        if (!checkUpdate) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result GetAdminList(GetAdminListDto dto) {
        if (BaseContext.getCurrentId()==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        dto.checkParam();
        IPage<Admin> page=new Page<>(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<Admin> wrapper=new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(dto.getName())) {
            wrapper.like(Admin::getAdminName,dto.getName());
        }
        page=page(page,wrapper);
        Result result=new PageResponseResult(dto.getPage(),dto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());
        return result;
    }

    @Override
    public Result RemoveAdmin(Long id) {
        if (BaseContext.getCurrentId()==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        Admin checkAdmin = adminMapper.selectById(id);
        if (checkAdmin==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        boolean checkRemove = removeById(id);
        if (!checkRemove) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result UpdateAdmin(UpdateAdminDto dto) {
        if (BaseContext.getCurrentId()==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        Admin checkAdmin = adminMapper.selectById(dto.getId());
        if (checkAdmin==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        if (StringUtils.isNotBlank(dto.getName())) {
            checkAdmin.setAdminName(dto.getName());
        }
        if (StringUtils.isNotBlank(dto.getPassword())) {
            checkAdmin.setPassword(dto.getPassword());
            checkAdmin.setAdminPassword(DigestUtils.md5Hex(dto.getPassword()));
        }
        boolean checkUpdate = updateById(checkAdmin);
        if (!checkUpdate) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result AdminUpdateMeMessage(String name) {
        Admin checkAdmin = adminMapper.selectById(BaseContext.getCurrentId());
        checkAdmin.setAdminName(name);
        boolean checkUpdate = updateById(checkAdmin);
        if (!checkUpdate) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result SaveAdmin(SaveAdminDto dto) {
        if (BaseContext.getCurrentId()==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        Admin admin=new Admin();
        admin= admin.builder()
                .adminName(dto.getName())
                .password(dto.getPassword())
                .adminPassword(DigestUtils.md5Hex(dto.getPassword())).build();
        boolean checkSave = save(admin);
        if (!checkSave) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result RemoveAdminArr(String[] ids) {
        if (BaseContext.getCurrentId()==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        for (String id:ids) {
            Admin checkAdmin = adminMapper.selectById(id);
            if (checkAdmin==null) {
                return Result.errorResult(Code.DATA_NOT_EXIST);
            }
            boolean checkRemove = removeById(id);
            if (!checkRemove) {
                return Result.okResult(Code.SERVER_ERROR);
            }

        }
        return Result.okResult(Code.SUCCESS);
    }
}




